<template>
  <div class="wechat">
    <div class="wechat_card">
      <!-- 按钮部分 -->
      <el-row :gutter="20"
              class="wechat_card_head"
              type="flex">
        <el-col :span="5">
          <el-select v-model="currentRounte"
                     placeholder="选择巡逻路线"
                     @change="changeRounte"
                     size="medium">
            <el-option v-for="item in this.rounteList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-col>

        <el-button v-has="'6473'"
                   v-if="!isEdit"
                   @click="showEditDialog()"
                   type="warning"
                   icon="el-icon-edit"
                   size="medium"></el-button>
        <el-button v-has="'6472'"
                   v-if="!isEdit"
                   @click="deleteRounteRecordById"
                   type="danger"
                   icon="el-icon-delete"
                   size="medium"></el-button>
        <el-button v-has="'6471'"
                   v-if="!isEdit"
                   @click="addRounteDialogVisible=true"
                   type="primary"
                   icon="el-icon-circle-plus-outline"
                   size="medium">添加巡逻路线</el-button>
        <el-button v-if="isEdit"
                   @click="addDefaultRounte"
                   type="primary"
                   icon="el-icon-circle-plus-outline"
                   size="medium">添加默认路径</el-button>
        <el-button v-if="isEdit"
                   @click="addPolylinePoint"
                   type="success"
                   size="medium"
                   icon="el-icon-finished">确认保存</el-button>

        <div class="tools_head">
          <el-button v-has="'6474'"
                     v-if="!isEdit"
                     @click="ChangeEdit"
                     type="success"
                     size="medium">开启打卡点编辑模式</el-button>
          <el-button v-else
                     @click="ChangeEdit"
                     type="danger"
                     size="medium">关闭打卡点编辑模式</el-button>
        </div>
      </el-row>
      <!-- 添加巡逻路线对话框 -->
      <el-dialog title="添加巡逻路线"
                 :visible.sync="addRounteDialogVisible"
                 @close="addRounteDialogClosed"
                 width="40%">
        <!-- 内容主体区 -->
        <el-form :model="addRounteForm"
                 :rules="addRounteFormRules"
                 ref="addRounteFormRef"
                 label-width="80px"
                 label-position="right">
          <el-form-item label="路线名称"
                        prop="name">
            <el-input v-model="addRounteForm.name"></el-input>
          </el-form-item>
          <el-form-item label="描述"
                        prop="describe">
            <el-input type="textarea"
                      v-model="addRounteForm.describe"></el-input>
          </el-form-item>
          <el-form-item label="备注"
                        prop="memo">
            <el-input type="textarea"
                      v-model="addRounteForm.memo"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="addRounteDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="addRounteRecord">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑巡逻路线对话框 -->
      <el-dialog title="编辑巡逻路线"
                 :visible.sync="editRounteDialogVisible"
                 @close="editRounteDialogClosed"
                 width="40%">
        <!-- 内容主体区 -->
        <el-form :model="editRounteForm"
                 :rules="editRounteFormRules"
                 ref="editRounteFormRef"
                 label-width="80px"
                 label-position="right">
          <el-form-item label="路线名称"
                        prop="name">
            <el-input v-model="editRounteForm.name"></el-input>
          </el-form-item>
          <el-form-item label="描述"
                        prop="describe">
            <el-input type="textarea"
                      v-model="editRounteForm.describe"></el-input>
          </el-form-item>
          <el-form-item label="备注"
                        prop="memo">
            <el-input type="textarea"
                      v-model="editRounteForm.memo"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editRounteDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="editRounteRecord">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 地图部分 -->
      <baidu-map class="map"
                 :center="center"
                 :zoom="18"
                 :scroll-wheel-zoom="true"
                 @ready="handler"
                 style="margin-top:10px">
        <bm-polyline :path="pointPositionList"
                     stroke-color="red"
                     :stroke-opacity="0.5"
                     :stroke-weight="2"
                     :editing="isEdit"
                     :icons="icons"
                     @lineupdate="updatePolylinePath"></bm-polyline>
        <!-- 地图类型选择控件 -->
        <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"
                     anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
        <!-- 略缩图控件 -->
        <bm-overview-map anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
                         :isOpen="true"></bm-overview-map>
        <!-- 全景控件 -->
        <bm-panorama></bm-panorama>
        <!-- 缩放控件 -->
        <!-- <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT" :offset="{width:-10,height:30}"></bm-navigation> -->
        <!-- 版权信息控件 -->
        <!-- <bm-copyright anchor="BMAP_ANCHOR_TOP_RIGHT"
                      :copyright="[{id: 1, content: 'Copyright Message', bounds: {ne: {lng: 110, lat: 40}, sw:{lng: 0, lat: 0}}}, {id: 2, content: '<a>666</a>'}]">
        </bm-copyright> -->

        <!-- 路书 -->
        <bml-lushu v-if="isLuShuVisble"
                   @stop="reset"
                   :path="pointPositionList"
                   :icon="icon"
                   :play="play"
                   :rotation="true"
                   :speed="500"
                   :autoView="true">
        </bml-lushu>

        <!-- 点标注 -->
        <template v-for="(item,i) in pointPositionList">

          <!-- <bm-marker v-if="i==pointPositionList.length-1||i==0"
                   :position="item"
                   :dragging="false"
                   @click="look(item,i)"
                   :key="i"
                   
                   :icon="{url: 'http://developer.baidu.com/map/jsdemo/img/fox.gif', size: {width: 300, height: 157}}">
        </bm-marker> -->
          <bm-marker :position="item"
                     :dragging="isEdit"
                     @click="look(item,i)"
                     :key="i">
            <bm-label v-if="i==0"
                      content="起点"
                      :labelStyle="{color: 'green', fontSize : '12px'}"
                      :offset="{width: -10, height: 30}" />
            <bm-label v-if="i==pointPositionList.length-1"
                      content="终点"
                      :labelStyle="{color: 'red', fontSize : '12px'}"
                      :offset="{width: -10, height: 30}" />
          </bm-marker>
        </template>
        <!-- 信息框 -->
        <bm-info-window :show="show"
                        @close="infoWindowClose"
                        @open="infoWindowOpen"
                        :position="windowPosition">
          <p>打卡点排序：{{windowRank}}
          </p>
          <p v-if="!editInputVisble">描述：{{windowInfo}}
            <el-button @click="editwindowInfo"
                       icon="el-icon-edit"
                       size="mini"
                       style="margin-left:20px"></el-button>
          </p>
          <p v-if="editInputVisble">描述：
            <el-input type="textarea"
                      :rows="2"
                      placeholder="请输入内容"
                      v-model="windowInfo"
                      style="margin-top:10px">
            </el-input>
          </p>
          <p v-if="editInputVisble">
            <el-button @click="editwindowInfo"
                       size="mini"
                       style="margin-right:10px">取消</el-button>
            <el-button @click="editwindowInfoById"
                       type="primary"
                       size="mini"
                       style="margin-left:120px">确认</el-button>
          </p>
        </bm-info-window>

      </baidu-map>

    </div>
  </div>
</template>

<script>
import { BmlLushu } from 'vue-baidu-map'
export default {
  components: {
    BmlLushu
  },
  data () {
    return {
      center: { lng: 116.018822, lat: 29.685495 },
      // icons:[el-icon-s-flag],
      // icons: [(symbol: Symbol, offset: string, repeat: string, fixedRotation: boolean),],
      icons: [],
      //打卡点详细信息列表
      pointInfoData: {},
      // 打卡点坐标列表
      pointPositionList: [
        // { lng: 116.018822, lat: 29.685495 },
        // { lng: 116.01596, lat: 29.685221 },
        // { lng: 116.016297, lat: 29.684256 },

      ],


      //当前窗口坐标
      windowPosition: {},
      // 未修饰的窗口坐标
      windowPosition2: '',
      // 当前打卡点在打卡点数组中的顺序
      windowIndex: 0,
      // 当前窗口表单
      windowForm: {},
      // 窗口：打卡点描述
      windowInfo: '',
      //窗口：打卡点排序
      windowRank: '',
      //窗口：当前打卡点id
      windowId: '',
      //窗口：打卡点描述编辑文本框是否可见
      editInputVisble: false,



      // 路书配置：路书是否显示
      isLuShuVisble: true,
      //路书配置：路书是否播放
      play: true,
      //路书图标
      icon: {
        // url: 'http://api.map.baidu.com/library/LuShu/1.2/examples/car.png',
        url: 'http://r46r9i6c2.hn-bkt.clouddn.com/%E4%BF%9D%E5%AE%89%20%283%29.png',
        size: { width: 52, height: 26 },
        // opts: { anchor: { width: 27, height: 13 } }
        opts: { anchor: { width: 30, height: 30 } }
      },


      // 是否显示点标注
      show: false,
      // 是否开启编辑模式
      isEdit: false,
      // 记录列表分页区的参数
      queryInfo: {
        //搜索条件
        query: "",
        // 当前页码
        pageNum: 1,
        //每页显示条数
        pageSize: 10,
      },
      condition: '',
      // 当前显示的巡逻路线
      currentRounte: '',
      // 添加巡逻打卡点表单
      addForm: {},
      // 添加巡逻路线表单
      addRounteForm: {},
      // 是否显示添加路线对话框
      addRounteDialogVisible: false,
      // 编辑巡逻路线表单
      editRounteForm: {},
      //是否显示编辑路线对话框
      editRounteDialogVisible: false,
      // 巡逻路线列表
      rounteList: [],



      // 添加表单校验规则
      addRounteFormRules: {
        name: [
          { required: true, message: '请输入路线名称', trigger: 'blur' },
          { min: 1, max: 25, message: '路线长度在1到25个字符串之间', trigger: 'blur' }
        ],
      },
      // 编辑表单校验规则
      editRounteFormRules: {
        name: [
          { required: true, message: '请输入路线名称', trigger: 'blur' },
          { min: 1, max: 25, message: '路线长度在1到25个字符串之间', trigger: 'blur' }
        ],
      },

    }
  },
  created () {
    this.getTableList();
  },
  methods: {
    handler ({ BMap, map }) {
      console.log(BMap, map)
      var sy = new BMap.Symbol(BMap_Symbol_SHAPE_FORWARD_OPEN_ARROW, {
        scale: 0.5, // 图标缩放大小
        strokeColor: "#fff", // 设置矢量图标的线填充颜色
        strokeWeight: "3" // 设置线宽
      });
      var icons = new BMap.IconSequence(sy, "5%", "15%");
      this.icons.push(icons)
      this.icons.push(icons)
      this.icons.push(icons)
      console.log(this.icons)

    },
    //获取巡逻路线列表
    async getTableList () {
      // 获取巡逻路线列表
      const { data: res0 } = await this.$http.get("SecurityrounteAction/getBasicInfos")
      if (!res0.success) return this.$message.error('获取巡逻路线列表失败')
      this.rounteList = res0.rows
      console.log(this.rounteList)


    },


    // 添加巡逻路线
    addRounteRecord () {
      this.$refs.addRounteFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post("SecurityrounteAction/addObject", this.addRounteForm)
        console.log(res)
        if (!res.success) return this.$message.error('添加巡逻路线失败！')
        this.$message.success('添加巡逻路线成功！')
        // 隐藏添加记录的对话框
        this.addRounteDialogVisible = false
        // 重新获取记录列表数据
        this.getTableList()
      })

    },
    // 监听添加巡逻路线对话框的关闭事件：重置表单
    addRounteDialogClosed () {
      this.$refs.addRounteFormRef.resetFields()
    },


    // 删除当前巡逻路线
    async deleteRounteRecordById () {
      // 如果尚未选择路线，提示用户先选择路线
      if (this.currentRounte == '')
        return this.$message.error("请选择巡逻路线！")
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该条巡逻路线, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，返回值为字符串confirm
      // 如果用户取消删除，返回值未字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.post("SecurityrounteAction/deleteByIds", { ids: this.currentRounte })
      if (!res.success) return this.$message.error('删除路线失败！')
      this.$message.success('删除当前巡逻路线成功！')
      this.getTableList()

    },


    // 查看修改记录（当前路线）
    async showEditDialog () {
      // 如果尚未选择路线，提示用户先选择路线
      if (this.currentRounte == '')
        return this.$message.error("请选择巡逻路线！")
      const { data: res } = await this.$http.post("SecurityrounteAction/getObjectById", { id: this.currentRounte })
      if (!res.success)
        return this.$message.error('获取路线信息失败')
      this.editRounteForm = res.rows[0]
      this.editRounteDialogVisible = !this.editRounteDialogVisible
    },
    // 确认修改当前记录
    editRounteRecord () {
      this.$refs.editRounteFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改记录信息的数据请求
        const { data: res } = await this.$http.post("SecurityrounteAction/updateNoNull", this.editRounteForm)
        if (!res.success) return this.$message.error('更新巡逻路线信息失败！')
        // 提示修改成功
        this.$message.success('更新巡逻路线信息成功！')
        // 关闭对话框
        this.editRounteDialogVisible = false
        // 刷新数据列表
        this.getTableList()

      })
    },
    // 监听编辑巡逻路线对话框的关闭事件
    editRounteDialogClosed () {
      this.$refs.editRounteFormRef.resetFields()
    },


    // 变更路线
    async changeRounte () {
      // 关闭信息窗口
      this.show = false
      // 重置巡逻点列表
      this.pointPositionList = []
      //获取当前路线的巡逻点信息
      this.queryInfo.condition = `securityrountedetail.securityRounteId = "${this.currentRounte}"`;
      const { data: res } = await this.$http.get("SecurityrountedetailAction/getBasicInfos", { params: this.queryInfo })
      // 获取巡逻路线列表
      // const { data: res0 } = await this.$http.get("SecurityrounteAction/getBasicInfos")
      if (!res.success) return this.$message.error('获取巡逻打卡列表失败')
      // this.rounteList = res0.rows
      // console.log(this.rounteList)
      this.pointInfoData = res.rows
      // 处理pointInfoData中的数据，把点坐标数据给到pointList
      for (var i = 0; i < this.pointInfoData.length; i++) {
        var str = this.pointInfoData[i].position.split(',')
        var obj = { lng: 0, lat: 0 }
        obj.lng = parseFloat(str[0])
        obj.lat = parseFloat(str[1])
        console.log(obj)
        this.pointPositionList.push(obj)
        // 重新运行路书
        this.play = true
      }

      console.log(res)


    },
    // 编辑折线时更新打卡点个数
    updatePolylinePath (e) {
      this.pointPositionList = e.target.getPath()
      console.log(this.pointPositionList)
    },
    // 确认保存打卡路线
    async addPolylinePoint () {
      // 首先把数据库中该条路线所有信息删除
      // /deleteByParams?condition=securityRounteId=12
      // this.queryInfo.condition = `securityrountedetail.securityRounteId = "${this.currentRounte}"`
      this.condition = `securityrountedetail.securityRounteId = "${this.currentRounte}"`
      const { data: res0 } = await this.$http.post("SecurityrountedetailAction/deleteByParams", { condition: this.condition })
      if (!res0.success) return this.$message.error('删除数据库原打卡点记录失败！')
      // 再把现有的该条路线所有信息添加
      var pointList = []
      for (var i = 0; i < this.pointPositionList.length; i++) {
        pointList[i] = this.pointPositionList[i].lng + ',' + this.pointPositionList[i].lat
        this.addForm.position = pointList[i]
        this.addForm.securityRounteId = this.currentRounte
        this.addForm.rank = i
        const { data: res } = await this.$http.post("SecurityrountedetailAction/addObject", this.addForm)
        if (!res.success) return this.$message.error('添加失败')
        this.$message.success('保存打卡点成功！')

        // 重新获取记录列表数据
        // this.getTableList()

      }
      console.log(pointList)
      // this.pointPositionList.push({ lng: 116.404, lat: 39.915 })
    },
    // removeEventListener () {
    //   this.map.removeOverlay({ lng: 116.404, lat: 39.915 })
    // },
    //改变编辑模式
    ChangeEdit () {
      if (this.currentRounte == '')
        return this.$message.error("请先选择需要编辑的巡逻路线！")
      this.isEdit = !this.isEdit
      this.isLuShuVisble = !this.isLuShuVisble
      this.play = true
    },
    // 路书停止
    reset () {
      this.play = false
    },
    // 标注点的点击事件
    infoWindowClose () {
      this.show = false
      this.editInputVisble = false
    },
    infoWindowOpen () {
      this.show = true
    },
    look (item, i) {
      this.windowIndex = i
      this.windowPosition = item
      this.windowPosition2 = this.pointInfoData[i].position
      this.windowInfo = this.pointInfoData[i].info
      this.windowRank = this.pointInfoData[i].rank
      this.windowId = this.pointInfoData[i].id

      this.show = true;
    },
    //点击编辑当前点的描述
    editwindowInfo () {
      this.editInputVisble = true
    },
    // 确认编辑当前打卡点
    async editwindowInfoById () {
      this.windowForm.id = this.windowId
      this.windowForm.info = this.windowInfo
      this.windowForm.rank = this.windowRank
      this.windowForm.position = this.windowPosition2

      const { data: res } = await this.$http.post("SecurityrountedetailAction/updateNoNull", this.windowForm)
      if (!res.success) return this.$message.error('更新打卡点信息失败！')
      // 关闭描述编辑文本框
      this.editInputVisble = false
      // 重新获取当前路线的所有点信息
      this.changeRounte()
      // 重新获取当前点的信息
      // this.look(this.pointPositionList[this.windowIndex], this.windowIndex)
      // 更换路线会把窗口关掉，重新开启
      this.show = true
    },
    // 添加默认路线
    addDefaultRounte () {
      console.log(this.currentRounte)
      console.log(this.pointPositionList.length)
      // 选择了路线并且当前没有一条路径
      if (this.currentRounte != '' && this.pointPositionList.length == 0) {
        // 这条默认路径应该是数据库有一个表存储每个社区设定的一个默认路径，此处用写死的
        this.pointPositionList.push({ lng: 116.018822, lat: 29.685495 })
        this.pointPositionList.push({ lng: 116.020088, lat: 29.68623 })
      } else if (this.currentRounte == '') {
        this.$message.error("请先选择巡逻路线！")
      } else {
        console.log(this.pointPositionList)
        this.$message.error("当前已有路线，无需添加！")
      }
    }
  }
}
</script>
<style>
.map {
  width: 100%;
  height: 90%;
}
</style>
